package aip.ui.todo.srvc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;

import aip.core.dao.todo.TodoDao;
import aip.core.model.todo.Todo;
import aip.ui.todo.web.spring.TodoEditForm;
import aip.ui.todo.web.spring.TodoListForm;

import com.googlecode.horncomb.bean.paged.PagedList;
import com.googlecode.horncomb.bean.paged.PagedSetting;

/**
 * Todo form service
 * <p>
 * 负责人/principal:<br/>
 * 修改记录/revision:<br/>
 * 日期:<br/>
 * 修改人:<br/>
 * 修改说明:<br/>
 * @author
 * @version $Id$
 */
public class TodoFormService
{
    private TodoDao todoDao;

    /**
     * Todo列表
     * @param form
     *        表单对象
     * @return 列表页面数据
     * @throws Exception
     */
    public Map<String, Object> listReference(TodoListForm form)
            throws Exception
    {
        Map<String, Object> ref = new HashMap<String, Object>();
        PagedSetting ps = form.getPagedSettingMap().values().iterator().next();
        PagedList<List<? extends Todo>> result = this.todoDao.queryAll(ps
                .getOrder(), ps.getPage(), ps.getPageSize());
        ref.put("todoList", result.getSource()); //$NON-NLS-1$
        ref.put("totalRows", result.getNrOfElements()); //$NON-NLS-1$
        return ref;
    }

    /**
     * 删除选中的项
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void deleteItems(TodoListForm form) throws Exception
    {
        if (form.getSelectedIds().size() > 0)
        {
            this.todoDao.deleteByIds(form.getSelectedIds());
        }
    }

    /**
     * 获得Todo表单主对象
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void get(TodoEditForm form) throws Exception
    {
        if (form != null && form.getId() > 0)
        {
            Todo todo = this.todoDao.getById(form.getId());
            BeanUtils.copyProperties(todo, form);
        }
    }

    /**
     * 显示编辑Todo界面相关数据
     * @param form
     *        表单对象
     * @return 显示页面数据
     * @throws Exception
     */
    public Map<String, Object> showReference(TodoEditForm form)
            throws Exception
    {
        // other reference data
        Map<String, Object> ref = new HashMap<String, Object>();
        return ref;
    }

    /**
     * 保存Todo表单
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void save(TodoEditForm form) throws Exception
    {
        this.todoDao.save(form);
    }

    /**
     * 删除单个Todo
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void deleteItem(TodoEditForm form) throws Exception
    {
        this.todoDao.deleteById(form.getId());
    }

    /**
     * @param todoDao
     *        the todoDao to set
     */
    public void setTodoDao(TodoDao todoDao)
    {
        this.todoDao = todoDao;
    }
}
